using System;

namespace Battle
{
    public class FightController
    {
        private readonly Fighter _fighter1;
        private readonly Fighter _fighter2;

        private readonly Tablee _table1;
        private readonly Tablee _table2;

        private readonly ScoredTable _scoreTable;

        public FightController(Fighter fighter1, Fighter fighter2, Tablee table1, Tablee table2, ScoredTable scoreTable)
        {
            _fighter1 = fighter1;
            _fighter2 = fighter2;
            _table1 = table1;
            _table2 = table2;
            _scoreTable = scoreTable;
            _fighter1.Fighting += OnFighterShooting;
            _fighter2.Fighting += OnFighterShooting;
            _fighter1.Figh += OnFighterShotShot;
            _fighter2.Figh += OnFighterShotShot;
        }

        private void OnFighterShotShot(object sender, ShootingEventArgs e)
        {
            if (_scoreTable.FightHasEnded())
            {
                return;
            }
            var shooter = (Fighter)sender;
            var openent = shooter == _fighter1 ? _fighter2 : _fighter1;
            if (e.Result != ShotingEnum.Mis)
            {
                shooter.Shott();
            }
            else
            {
                openent.Shott();
            }
        }

        private void OnFighterShooting(object sender, ShootingEventArgs e)
        {
            var shooter = (Fighter)sender;
            Tablee oponentTable;
            Fighter openent;
            if (shooter == _fighter1)
            {
                openent = _fighter2;
                oponentTable = _table2;
            }
            else
            {
                openent = _fighter1;
                oponentTable = _table1;
            }
            var shotResult = oponentTable.OpenentShotAt(e.X, e.Y);
            e.Result = shotResult;
            if (_scoreTable.FightHasEnded())
                return;
        }

        public void NewFightOnController()
        {
            _table1.Mode = TableStageEnum.Preparation;
            _table2.Mode = TableStageEnum.Preparation;
            _table1.AddRndShips();
            _table2.AddRndShips();
            _fighter1.Delete();
            _fighter2.Delete();
            _scoreTable.NewFightOnTable();
        }

        public void StartFight()
        {
            var playerIndex = new Random(DateTime.Now.Millisecond).Next(1, 3);
            var player = playerIndex == 1 ? _fighter1 : _fighter2; 
            _table1.Mode = TableStageEnum.Fight;
            _table2.Mode = TableStageEnum.Fight;
            _scoreTable.NewFightOnTable();
            player.Shott();
        }
    }
}